﻿using System;
using System.Web.Mvc;
using Forest.Lion.Domain.Contracts;
using Forest.Lion.Web.Authentication;
using Forest.Lion.Web.Models.Auth;
using Microsoft.Practices.Unity;
using Forest.Lion.Data;
using Forest.Lion.Domain.Models;

namespace Forest.Lion.Web.Controllers {
    public class AuthController : Controller {

        private readonly IFormsAuthentication _formsAuthentication;
        private readonly IUserServices _userServices;


        [InjectionConstructor]
        public AuthController(IFormsAuthentication formsAuthentication,
                              IUserServices userServices) {
            this._formsAuthentication = formsAuthentication;
            this._userServices = userServices;
        }

        //
        // GET: /Auth/

        public ActionResult SignIn() {
            var model = new LoginFormModel();

            return View(model);
        }

        [HttpPost]
        public ActionResult SignIn(LoginFormModel model, string returnUrl) {
            if (ModelState.IsValid) {
                if (_userServices.ValidateUser(model.UserName, model.Password)) {

                    var user = _userServices.GetAuthenticatedUser(model.UserName);
                    _formsAuthentication.SetAuthCookie(this.HttpContext,
                                                           UserAuthenticationTicketBuilder.CreateAuthenticationTicket(
                                                               user));
                    if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                        return Redirect(returnUrl);
                    else
                        return RedirectToAction("Index", "Home");
                }
            }

            return View(model);
        }

        public ActionResult Register() {

            return View(new User());
        }

        [HttpPost]
        public ActionResult Register(User registerUser) {
            if (ModelState.IsValid) {
                if (_userServices.RegisterUser(registerUser) != null) {

                    var user = _userServices.GetAuthenticatedUser(registerUser.UserName);
                    _formsAuthentication.SetAuthCookie(this.HttpContext,
                                                             UserAuthenticationTicketBuilder.CreateAuthenticationTicket(
                                                                 user));
                    return this.RedirectToAction("Index", "Home");
                }
            }

            return View(registerUser);

        }

        public ActionResult SignOut() {
            this._formsAuthentication.Signout();
            return this.RedirectToAction("SignIn", "Auth");
        }

    }
}
